<template>
	<view class="profile-edit-container">
		
		<!-- 加载状态 -->
		<view v-if="loading" class="loading-container">
			<uni-icons type="spinner-cycle" size="40" color="#1989fa"></uni-icons>
			<text class="loading-text">加载中...</text>
		</view>
		
		<!-- 编辑表单 -->
		<view v-else class="form-container">
			<!-- 头像 -->
			<view class="form-item avatar-item">
				<view class="form-label">头像</view>
				<view class="avatar-box" @click="chooseAvatar">
					<image :src="formData.avatar || '/static/logo.png'" mode="aspectFill" class="avatar"></image>
					<view class="avatar-tip">点击更换</view>
				</view>
			</view>
			
			<!-- 用户名 -->
			<view class="form-item">
				<view class="form-label">用户名</view>
				<input 
					v-model="formData.username" 
					class="form-input" 
					placeholder="请输入用户名"
					maxlength="20"
				/>
			</view>
			
			<!-- 邮箱 -->
			<view class="form-item">
				<view class="form-label">邮箱</view>
				<input 
					v-model="formData.email" 
					class="form-input" 
					type="text"
					placeholder="请输入邮箱"
				/>
			</view>
			
			<!-- 手机号 -->
			<view class="form-item">
				<view class="form-label">手机号</view>
				<input 
					v-model="formData.phone" 
					class="form-input" 
					type="number"
					maxlength="11"
					placeholder="请输入手机号"
				/>
			</view>
			
			<!-- 分隔线 -->
			<view class="divider"></view>
			
			<!-- 修改密码部分 -->
			<view class="password-section">
				<view class="section-title">修改密码（选填）</view>
				
				<view class="form-item">
					<view class="form-label">原密码</view>
					<input 
						v-model="passwordData.oldPassword" 
						class="form-input" 
						type="password"
						password
						placeholder="请输入原密码"
					/>
				</view>
				
				<view class="form-item">
					<view class="form-label">新密码</view>
					<input 
						v-model="passwordData.newPassword" 
						class="form-input" 
						type="password"
						password
						placeholder="请输入新密码（6-20位）"
					/>
				</view>
				
				<view class="form-item">
					<view class="form-label">确认密码</view>
					<input 
						v-model="passwordData.confirmPassword" 
						class="form-input" 
						type="password"
						password
						placeholder="请再次输入新密码"
					/>
				</view>
			</view>
			
			<!-- 保存按钮 -->
			<view class="button-group">
				<button class="save-btn" @click="handleSave" :loading="saving">保存</button>
			</view>
		</view>
	</view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { userApi } from '../../common/api/index.js'

// 响应式数据
const loading = ref(true)
const saving = ref(false)
const formData = ref({
	username: '',
	email: '',
	phone: '',
	avatar: ''
})
const passwordData = ref({
	oldPassword: '',
	newPassword: '',
	confirmPassword: ''
})

// 获取用户信息
const getUserInfo = async () => {
	loading.value = true
	try {
		const response = await userApi.getUserInfo()
		if (response.message === '查询成功' && response.data) {
			formData.value = {
				username: response.data.username || '',
				email: response.data.email || '',
				phone: response.data.phone || '',
				avatar: response.data.avatar || ''
			}
		} else {
			uni.showToast({
				title: '获取用户信息失败',
				icon: 'none'
			})
		}
	} catch (err) {
		console.error('获取用户信息失败:', err)
		uni.showToast({
			title: '网络错误',
			icon: 'none'
		})
	} finally {
		loading.value = false
	}
}

// 选择头像
const chooseAvatar = () => {
	uni.chooseImage({
		count: 1,
		sizeType: ['compressed'],
		sourceType: ['album', 'camera'],
		success: (res) => {
			// 这里应该上传到服务器，获取URL
			// 暂时使用本地路径演示
			formData.value.avatar = res.tempFilePaths[0]
			
			// TODO: 实际项目中需要上传到服务器
			// uploadAvatar(res.tempFilePaths[0])
			
			uni.showToast({
				title: '头像已选择',
				icon: 'success'
			})
		}
	})
}

// 验证表单
const validateForm = () => {
	// 验证用户名
	if (!formData.value.username || formData.value.username.trim() === '') {
		uni.showToast({
			title: '请输入用户名',
			icon: 'none'
		})
		return false
	}
	
	// 验证邮箱格式
	if (formData.value.email) {
		const emailReg = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
		if (!emailReg.test(formData.value.email)) {
			uni.showToast({
				title: '邮箱格式不正确',
				icon: 'none'
			})
			return false
		}
	}
	
	// 验证手机号格式
	if (formData.value.phone) {
		const phoneReg = /^1[3-9]\d{9}$/
		if (!phoneReg.test(formData.value.phone)) {
			uni.showToast({
				title: '手机号格式不正确',
				icon: 'none'
			})
			return false
		}
	}
	
	// 如果要修改密码，验证密码
	if (passwordData.value.oldPassword || passwordData.value.newPassword || passwordData.value.confirmPassword) {
		if (!passwordData.value.oldPassword) {
			uni.showToast({
				title: '请输入原密码',
				icon: 'none'
			})
			return false
		}
		
		if (!passwordData.value.newPassword) {
			uni.showToast({
				title: '请输入新密码',
				icon: 'none'
			})
			return false
		}
		
		if (passwordData.value.newPassword.length < 6 || passwordData.value.newPassword.length > 20) {
			uni.showToast({
				title: '密码长度应为6-20位',
				icon: 'none'
			})
			return false
		}
		
		if (passwordData.value.newPassword !== passwordData.value.confirmPassword) {
			uni.showToast({
				title: '两次输入的密码不一致',
				icon: 'none'
			})
			return false
		}
	}
	
	return true
}

// 保存信息
const handleSave = async () => {
	if (!validateForm()) {
		return
	}
	
	saving.value = true
	
	try {
		// 构建提交数据
		const submitData = {
			username: formData.value.username,
			email: formData.value.email,
			phone: formData.value.phone,
			avatar: formData.value.avatar
		}
		
		// 如果修改密码，添加密码字段
		if (passwordData.value.oldPassword && passwordData.value.newPassword) {
			submitData.oldPassword = passwordData.value.oldPassword
			submitData.newPassword = passwordData.value.newPassword
		}
		
		const response = await userApi.updateProfile(submitData)
		
		if (response.status === 'success') {
			uni.showToast({
				title: '保存成功',
				icon: 'success'
			})
			
			// 更新本地存储的用户信息
			const userInfo = uni.getStorageSync('userInfo') || {}
			Object.assign(userInfo, response.data)
			uni.setStorageSync('userInfo', userInfo)
			
			// 清空密码字段
			passwordData.value = {
				oldPassword: '',
				newPassword: '',
				confirmPassword: ''
			}
			
			// 延迟返回
			setTimeout(() => {
				uni.navigateBack()
			}, 1000)
		} else {
			uni.showToast({
				title: response.message || '保存失败',
				icon: 'none'
			})
		}
	} catch (err) {
		console.error('保存失败:', err)
		uni.showToast({
			title: err.message || '网络错误',
			icon: 'none'
		})
	} finally {
		saving.value = false
	}
}

// 页面加载时获取用户信息
onMounted(() => {
	getUserInfo()
})
</script>

<style lang="scss" scoped>
.profile-edit-container {
	min-height: 100vh;
	background-color: #f5f5f5;
	
	.loading-container {
		padding: 200rpx 0;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		
		.loading-text {
			margin-top: 30rpx;
			font-size: 28rpx;
			color: #999;
		}
	}
	
	.form-container {
		padding: 30rpx;
		
		// 头像项
		.avatar-item {
			display: flex;
			flex-direction: row;
			align-items: center;
			padding: 40rpx 30rpx;
			
			.form-label {
				width: auto;
				margin-bottom: 0;
			}
			
			.avatar-box {
				margin-left: auto;
				display: flex;
				align-items: center;
				gap: 20rpx;
				
				.avatar {
					width: 120rpx;
					height: 120rpx;
					border-radius: 50%;
					background-color: #f0f0f0;
				}
				
				.avatar-tip {
					font-size: 26rpx;
					color: #1890ff;
				}
			}
		}
		
		// 表单项
		.form-item {
			background-color: #ffffff;
			padding: 30rpx;
			margin-bottom: 20rpx;
			border-radius: 12rpx;
			
			.form-label {
				font-size: 28rpx;
				color: #333;
				margin-bottom: 20rpx;
				font-weight: 500;
			}
			
			.form-input {
				width: 100%;
				height: 80rpx;
				padding: 0 20rpx;
				background-color: #f5f5f5;
				border-radius: 8rpx;
				font-size: 28rpx;
			}
		}
		
		// 分隔线
		.divider {
			height: 20rpx;
			background-color: transparent;
			margin: 20rpx 0;
		}
		
		// 密码修改区域
		.password-section {
			.section-title {
				font-size: 30rpx;
				color: #333;
				font-weight: 600;
				margin-bottom: 20rpx;
				padding: 0 10rpx;
			}
		}
		
		// 按钮组
		.button-group {
			margin-top: 60rpx;
			padding: 0 10rpx;
			
			.save-btn {
				width: 100%;
				height: 90rpx;
				background: #8cbefe;
				color: #ffffff;
				border-radius: 45rpx;
				font-size: 32rpx;
				font-weight: 500;
				border: none;
				
				&:active {
					opacity: 0.8;
				}
			}
		}
	}
}
</style>

